package org.example.base.common.controller;

import org.example.base.common.model.TRequestLogModel;
import org.example.base.common.model.TRoleModel;
import org.example.base.common.service.TRoleService;
import org.example.core.controller.BaseController;
import org.example.core.enums.ApiResult;
import org.example.core.exception.ErrorException;
import org.example.core.mysql.SearchPageResult;
import org.example.core.mysql.Where;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Description:
 * Date: 2024/1/12 23:53
 */
@RestController
@RequestMapping("/role")
public class TRoleController extends BaseController<String, TRoleService, TRoleModel> {

    @Autowired
    private TRoleService tRoleService;

    @PostMapping("/addMenus")
    public ApiResult addMenus(@RequestBody Map<String,Object> params){
        Object menuIds = params.get("menuIds");
        if (ObjectUtils.isEmpty(menuIds)){
            throw new ErrorException("menuIds不能为空");
        }
        Object roleId = params.get("roleId");
        if (ObjectUtils.isEmpty(roleId)){
            throw new ErrorException("roleId不能为空");
        }
        tRoleService.addMenus(params);
        return ApiResult.success();
    }

    @GetMapping("/getDetail")
    public ApiResult getDetail(String id){
        return ApiResult.success(tRoleService.getDetail(id));
    }

    @Override
    public ApiResult searchPage(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam(required = false) Map<String, Object> params) {
        SearchPageResult<TRoleModel> result = new SearchPageResult<>();
        Object name = params.get("name");
        Where where  = Where.build().field("del_flag").equal(0);
        if (!ObjectUtils.isEmpty(name)){
            where.and().field("name").equal(name);
        }
        int totalCount = tRoleService.count(where);
        List<TRoleModel> resultList = tRoleService.search(where.limit(page, limit));
        result.setPage(page);
        result.setLimit(limit);
        result.setTotalCount(totalCount);
        result.setList(resultList);
        return ApiResult.success(result);
    }
}
